<?php
require_once("../include/main.php");

if(isset($_GET['op'])) {
	switch($_GET['op']) {
	case 'login':
		if(isset($_POST)) {
			$username = $_POST['u_name'];
			$password = $_POST['u_pwd'];
			$sql = "SELECT * FROM user WHERE username='".$username."'";
			//print $sql;
			$res = $db->fetch($sql);
			$pwd = md5(md5($password));
			if($res) {
				if($pwd==$res['password']) {
					$_SESSION['id'] = $res['id'];
					$_SESSION['u'] = $res['username'];
					$_SESSION['n'] = $res['name'];
					$_SESSION['t'] = $res['type'];
					echo "0";
				} else echo "1";
			} else echo "2";
		}
		break;
	case 'logout':
		unset($_SESSION['id']);
		unset($_SESSION['u']);
		unset($_SESSION['t']);
		echo "登出成功";
		break;
	case 'stat':	//get the login state of user
		if(isset($_SESSION['id'])) {
			$res = array();
			$res['id'] = $_SESSION['id'];
			$res['u'] = $_SESSION['u'];
			$res['n'] = $_SESSION['n'];
			$res['t'] = $_SESSION['t'];
			echo json_encode($res);
		}else echo false;
		break;
	case 'up':	//Update Password
		if(isset($_POST)) {
			//print_r($_POST);
			$password = trim($_POST['u_pwd']);
			$new = trim($_POST['u_newpwd']);
			$sql = "SELECT * FROM user WHERE id=".$_SESSION['id'];
			//print $sql;
			$res = $db->fetch($sql);
			if($res['password'] != md5(md5($password))) {
				echo '1';	//current password is wrong
			} else if($new=='') {
				echo '2';	//new password is empty
			} else {
				$sql = "UPDATE user SET password='".md5(md5($new))."' WHERE id=".$_SESSION['id'];
				//print $sql;
				$r = $db->execute($sql);
				if($r) echo '0';
			}
		}
		break;
	}
}